package com.zl.app.controller;

import com.alibaba.fastjson.JSON;
import com.zl.app.model.AppUserModel;
import com.zl.app.service.AppUserService;
import com.zl.common.annotation.Log;
import com.zl.common.config.ZlConfig;
import com.zl.common.constant.UserConstants;
import com.zl.common.core.domain.AjaxResult;
import com.zl.common.core.domain.entity.SysUser;
import com.zl.common.enums.BusinessType;
import com.zl.common.utils.SecurityUtils;
import com.zl.common.utils.StringUtils;
import com.zl.common.utils.file.FileUploadUtils;
import com.zl.common.utils.file.FileUtils;
import com.zl.system.service.ISysUserService;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * App用户相关控制类
 *
 * @author zl
 */
@RestController
@RequestMapping("/app")
public class AppUserController {


    @Autowired
    private ISysUserService userService;

    @Autowired
    private AppUserService appUserService;


    /**
     * App注册账号
     * @param request
     * @param files
     * @return
     */
    @PostMapping("app-register")
    public AjaxResult appRegister(HttpServletRequest request, @RequestParam("file") MultipartFile[] files){
        Map<String,String> parmMap=new HashMap<String,String>();
        Map<String,String[]> map= request.getParameterMap();
        //参数名称
        Set<String> key=map.keySet();
        //参数迭代器
        Iterator<String> iterator = key.iterator();
        while(iterator.hasNext()){
            String k=iterator.next();
            parmMap.put(k, map.get(k)[0]);
        }
        AppUserModel appUserModel= JSON.parseObject(JSON.toJSONString(parmMap),AppUserModel.class);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(appUserModel.getUserName())))
        {
            return AjaxResult.error("新增用户'" + appUserModel.getUserName() + "'失败，登录账号已存在");
        }

        // 上传文件路径
        String filePath = ZlConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = null;

        int data = 0;
        try {
            fileName = FileUploadUtils.upload(filePath, files[0]);
            String path=fileName.split("/profile")[1];
            //压缩图片再保存outputQuality(1f) 越接近1，图片质量越高
            Thumbnails.of(files[0].getInputStream()).scale(0.5).outputQuality(1f).outputFormat("jpg").toFile(new File(ZlConfig.getUploadPathApp(),path));
            appUserModel.setAvatar(path);
            data=appUserService.insertAppUser(appUserModel);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return AjaxResult.success(data);
    }

    /**
     * App修改资料
     * @param request
     * @param files
     * @return
     */
    @PostMapping("modify-data")
    public AjaxResult appModifyData(HttpServletRequest request, @RequestParam("file") MultipartFile[] files){
        Map<String,String> parmMap=new HashMap<String,String>();
        Map<String,String[]> map= request.getParameterMap();
        //参数名称
        Set<String> key=map.keySet();
        //参数迭代器
        Iterator<String> iterator = key.iterator();
        while(iterator.hasNext()){
            String k=iterator.next();
            parmMap.put(k, map.get(k)[0]);
        }
        AppUserModel appUserModel= JSON.parseObject(JSON.toJSONString(parmMap),AppUserModel.class);
        // 上传文件路径
        String filePath = ZlConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = null;

        int data = 0;
        try {
                fileName = FileUploadUtils.upload(filePath, files[0]);
                String path=fileName.split("/profile")[1];
                //压缩图片再保存outputQuality(1f) 越接近1，图片质量越高
                Thumbnails.of(files[0].getInputStream()).scale(0.5).outputQuality(1f).outputFormat("jpg").toFile(new File(ZlConfig.getUploadPathApp(),path));
                appUserModel.setAvatar(path);
            data=appUserService.updateAppUser(appUserModel);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return AjaxResult.success(data);
    }





    /**
     * 找回密码
     * @param userName
     * @param password
     * @return
     */
    @GetMapping("resetPwd")
    public AjaxResult resetPwd(@RequestParam("userName") String userName, @RequestParam("password") String password ){
        return appUserService.resetPwd(userName, password);
    }

    /**
     * app修改用户
     */
    @PostMapping("updateAppUser")
    public AjaxResult updateAppUser(@RequestBody AppUserModel appUserModel)
    {
        appUserModel.setUpdateBy(appUserModel.getUserName());
        return AjaxResult.success(appUserService.updateAppUser(appUserModel));
    }

}
